package john.wenzi.server.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.derby.tools.sysinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import john.wenzi.server.entity.FileUploadEntity;
import john.wenzi.server.service.Impl.FileUploadServiceImpl;

public class DownloadServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	public static Logger logger = LoggerFactory.getLogger(DownloadServlet.class);
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("下载文件开始");
	    InputStream in = null;
	    OutputStream out = null;
	    FileUploadServiceImpl fileUploadServiceImpl = new FileUploadServiceImpl(); 
	    try{
	      request.setCharacterEncoding("utf-8"); 
	      response.setCharacterEncoding("utf-8"); 
	      response.setContentType("application/octet-stream");
	       
	      String fileName = request.getHeader("fileName");
	      logger.info("下载文件参数："+fileName);
	      //获取文件信息，得到数字信封
	      FileUploadEntity fileUploadEntity = fileUploadServiceImpl.findUploadRecord(fileName);
	      File file = new File(fileUploadEntity.getFilePath()+"/" + fileName);
	      response.setContentLength((int) file.length());
	      response.setHeader("Accept-Ranges", "bytes");
	      response.setHeader("entryptDigitalEnvelope", fileUploadEntity.getEncryptDigitalEnvelope());
	      int readLength = 0;
	       
	      in = new BufferedInputStream(new FileInputStream(file));
	      out = new BufferedOutputStream(response.getOutputStream());
	       
	      byte[] buffer = new byte[1024];
	      while ((readLength=in.read(buffer)) > 0) {
	        byte[] bytes = new byte[readLength];
	        System.arraycopy(buffer, 0, bytes, 0, readLength);
	        out.write(bytes);
	      }
	      out.flush();
	        
	    }catch(Exception e){
	      response.setStatus(410);
	      logger.info("下载文件出现异常："+e.getMessage());
	      e.printStackTrace();
	    }finally {
	    	try {
		      if (in != null) {
		          in.close();
		      }
		      if (out != null) {
			      out.close();
		      }
	        } catch (IOException e) {
	        }
	   }
	}

}
